package com.shop.loan.handler;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.shop.loan.mapper.LoanOrderBillByMybatisMapper;
import com.shop.loan.mapper.LoanOrderByMybatisMapper;
import com.shop.loan.mapper.LoanOrderPayLogByMybatisMapper;
import com.shop.loan.mapper.UserBankByMybatisMapper;
import com.shop.loan.model.common.Code;
import com.shop.loan.model.common.ResResult;
import com.shop.loan.model.entity.LoanOrderBillByMybatis;
import com.shop.loan.model.entity.LoanOrderByMybatis;
import com.shop.loan.model.entity.UserBankByMybatis;
import com.shop.loan.model.enums.PayType;
import com.shop.loan.model.vo.PayVo;
import com.shop.loan.model.vo.WithholdByOneVo;
import com.shop.loan.redis.RedisCache;
import com.shop.loan.redis.RedisLockUtil;
import com.shop.loan.redis.RedisUtil;
import com.shop.loan.service.PayService;
import com.shop.loan.util.Util;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import redis.clients.jedis.Jedis;
import xyz.erupt.annotation.fun.OperationHandler;
import xyz.erupt.upms.service.EruptUserService;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.List;
import java.util.UUID;

@Slf4j
@Service
public class WithholdByOneHandler implements OperationHandler<Object, WithholdByOneVo> {

    @Resource
    RedisLockUtil redisLockUtil;

    @Resource
    RedisUtil redisUtil;

    @Resource
    EruptUserService eruptUserService;

    @Resource
    LoanOrderByMybatisMapper loanOrderByMybatisMapper;

    @Resource
    UserBankByMybatisMapper userBankByMybatisMapper;

    @Resource
    PayService payService;

    @Resource
    LoanOrderBillByMybatisMapper loanOrderBillByMybatisMapper;

    @Resource
    LoanOrderPayLogByMybatisMapper loanOrderPayLogByMybatisMapper;

    @Override
    public String exec(List<Object> data, WithholdByOneVo withholdVo, String[] param) {
        if (data == null || data.size() == 0) {
            return "msg.error('未选中数据')";
        }
        if (withholdVo.getMoney().doubleValue() <= 0) {
            return "msg.error('代扣金额异常')";
        }
        Jedis jedis = redisUtil.getJedis();
        String lockKey = RedisCache.withholdAdminLock;
        String lockValue = UUID.randomUUID().toString();
        String info = "";
        try {
            if (!redisLockUtil.lock(jedis, lockKey, lockValue)) {
                return "msg.error('请稍后再操作')";
            }
            JSONObject jsonObject = JSON.parseObject(JSON.toJSONString(data.get(0)));
            Long id = jsonObject.getLongValue("id");
            LoanOrderByMybatis loanOrderByMybatis = loanOrderByMybatisMapper.selectByPrimaryKey(id);

//                List<UserBankByMybatis> userBankByMybatisList = userBankByMybatisMapper.selectByUser(loanOrderByMybatis.getUserId());
//                if (userBankByMybatisList == null || userBankByMybatisList.size() <= 0) {
//                    info = info + ",【" + id + "-该客户未绑卡】";
//                    continue;
//                }

            UserBankByMybatis userBankByMybatis = userBankByMybatisMapper.selectByPrimaryKey(withholdVo.getUserBank().getId());
            if (userBankByMybatis == null || userBankByMybatis.getIsDelete()) {
                return "msg.error('用户订单银行卡为空')";
            }

            PayVo payVo = new PayVo();
            payVo.setOpIp(loanOrderByMybatis.getOrderIp());
            payVo.setOrderId(loanOrderByMybatis.getId());
            payVo.setPayType(withholdVo.getPayType());
            payVo.setOpId(loanOrderByMybatis.getUserId());
            payVo.setPFrom(loanOrderByMybatis.getPFrom());
            payVo.setBindCardId(userBankByMybatis.getProtocol());
            payVo.setAmount(withholdVo.getMoney());
            payVo.setRemark(eruptUserService.getCurrentUid() + "-代扣");
            ResResult payRes = payService.readyPay(payVo, true);
            if (payRes.getCode().intValue() == Code.SUCCESS.getCode().intValue()) {
                info = "【" + id + "-已提交】";
            } else {
                info = "【" + id + "-" + payRes.getMsg() + "】";
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.error(Util.GetErrorDetails(e));
        } finally {
            if (jedis != null) {
                redisLockUtil.release(jedis, lockKey, lockValue);
                jedis.close();
            }
        }
        return "alert('" + info + "')";
    }


    @Override
    public WithholdByOneVo eruptFormValue(List<Object> data, WithholdByOneVo withholdVo, String[] param) {
        Object item = data.get(0);
        JSONObject jsonObject = JSON.parseObject(JSON.toJSONString(item));
        Long id = jsonObject.getLongValue("id");

        LoanOrderByMybatis loanOrderByMybatis = loanOrderByMybatisMapper.selectByPrimaryKey(id);
        LoanOrderBillByMybatis loanOrderBillByMybatis = loanOrderBillByMybatisMapper.selectFirstUnPay(id);

        if (loanOrderByMybatis == null || loanOrderBillByMybatis == null) {
            return withholdVo;
        }

        BigDecimal periodPayMoney = loanOrderPayLogByMybatisMapper.selectSumByBillId(loanOrderBillByMybatis.getId(), null, PayType.principal_interest.getType());
        periodPayMoney = periodPayMoney == null ? BigDecimal.ZERO : periodPayMoney;

        withholdVo.setUserId(loanOrderByMybatis.getUserId());
        withholdVo.setOrderId(loanOrderByMybatis.getId());

        withholdVo.setTotalMoney(loanOrderByMybatis.getMoney().add(loanOrderByMybatis.getRateMoney()).add(loanOrderByMybatis.getShopMoney()));
        withholdVo.setPayMoney(loanOrderByMybatis.getPayMoney());
        withholdVo.setPeriod(loanOrderBillByMybatis.getPeriod());
        withholdVo.setTotalPeriod(loanOrderBillByMybatis.getTotalPeriod());
        withholdVo.setPeriodMoney(loanOrderBillByMybatis.getMoney());
        withholdVo.setPeriodRateMoney(loanOrderBillByMybatis.getRateMoney());
        withholdVo.setPeriodPayMoney(periodPayMoney);
        withholdVo.setPeriodDiscountMoney(loanOrderBillByMybatis.getDiscountsMoney() == null ? BigDecimal.ZERO : loanOrderBillByMybatis.getDiscountsMoney());
        loanOrderBillByMybatis.setPayMoney(periodPayMoney);
        withholdVo.setPeriodUnMoney(Util.getUnPayMoneyByPi(loanOrderBillByMybatis));
        withholdVo.setShopMoney(loanOrderByMybatis.getShopMoney());
        withholdVo.setPayMoneyByGoods(loanOrderByMybatis.getShopMoney());
        return withholdVo;
    }


}
